#include "tourguide.h"
#include <QStyleOption>
#include <QDebug>
#include <QColor>
TourGuide::TourGuide(QWidget *w, QWidget *parent) : QWidget(parent)
{
    m_MainWindows = w;
    m_GuidancePopup = new GuidancePopup(nullptr);
    QObject::connect(m_GuidancePopup, &GuidancePopup::signal_mouseButtonPressed,
                     this, &TourGuide::slot_mouseButtonPressed);
    //QObject::connect(ui->next, &GuidancePopup::signal_mouseButtonPressed,
    //                 this, &TourGuide::slot_mouseButtonPressed);

}

void TourGuide::onAddWidgetStep(QList<QWidget*> widgets, QStringList contentList, int steps)
{
    m_ListWidgetSteps << widgets;
    m_ListWidgetStrList << contentList;
    m_ListWidgetIndex << steps;
}

void TourGuide::paintEvent(QPaintEvent *event)
{
    Q_UNUSED(event);
    if (m_index < 0 || m_index >= m_ListWidgetSteps.size())
        return;

    QPainter painter(this);
    painter.setRenderHint(QPainter::Antialiasing);
    painter.setPen(Qt::NoPen);
    // 设置半透明覆盖层的颜色和透明度
    painter.setBrush(QColor(0, 0, 0, 100));
    // 绘制整个窗口的半透明覆盖层
    QRegion maskedRegion(0,0,width(),height());
    // 获取当前激活步骤的所有控件
    const QList<QWidget*>& currentWidgets = m_ListWidgetSteps[m_index];
    for (QWidget *widget : currentWidgets) {
        if (!widget)
            continue;

        // 将控件的位置映射到当前窗口的坐标系中
        QPoint guidePos = widget->mapTo(m_MainWindows, QPoint(0, 0));
        QRect rect(guidePos.x(), guidePos.y(), widget->width(), widget->height());
        maskedRegion = maskedRegion.subtracted(QRegion(rect));
        setMask(maskedRegion);
        // 将当前激活步骤的控件的区域内容清除，使其成为完全透明
    }
    painter.drawRect(this->rect());
    drawPopup(painter, m_index);
}

void TourGuide::mousePressEvent(QMouseEvent *event)
{
    QWidget::mousePressEvent(event);
    if (event->type() == QMouseEvent::MouseButtonPress) {
        slot_mouseButtonPressed();
    }
}

void TourGuide::drawPopup(QPainter& painter, int step)
{
    Q_UNUSED(painter);
    if(m_ListWidgetStrList.size() < step)
    {
        return ;
    }
    QString title;
    title = m_ListWidgetStrList.at(step).join("\n");

    m_GuidancePopup->setTitle(title);
    m_GuidancePopup->setStep(step,m_ListWidgetStrList.size());
    m_GuidancePopup->exec();
}

void TourGuide::slot_mouseButtonPressed()
{
    this->update();
    if (m_index + 1 < m_ListWidgetSteps.size()) {
        m_index++;
    }
    else {
        m_GuidancePopup->close();
        this->close();
        m_MainWindows->show();
    }
}
